package com.chuan.base.controller;

import java.io.File;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;

import com.chuan.base.config.YamlConfig;
import com.chuan.base.util.AutoSendMail;
import com.google.common.collect.Lists;
import com.shuodao.common.config.CommonConfig;
import com.shuodao.common.util.DateTimeUtil;
import com.shuodao.common.util.RequestUtil;
import com.shuodao.common.util.TemplateUtil;

@Controller
public class BaseController {

	private static final Logger LOGGER = LoggerFactory.getLogger(BaseController.class);
	protected static final String NAMESPACE = "pc";
	public static final int PAGE_LENGTH = 20;
	public final String REG = "[a-zA-Z0-9_]*"; // 匹配是否符合快递单号，只能包含字母数字下划线

	@Resource
	protected YamlConfig yamlConfig;

	private static final String SESSION_USER = "user";

	public static final String SESSION_KEY_WEIXIN_USER = "weixinUser";

	protected String ftl(String ftlFileName) {
		return NAMESPACE + "/" + ftlFileName;
	}

	public static String replaceBlank(String str) {
		String dest = "";
		if (str != null) {
			Pattern p = Pattern.compile("\\s*|\t|\r|\n");
			Matcher m = p.matcher(str);
			dest = m.replaceAll("");
		}
		return dest;
	}

	/**
	 * 拼接url
	 * 
	 * @param objects
	 * @return
	 */
	public static String joinToStr(Map<String, Object> urlMap) {
		String str = "";
		for (String key : urlMap.keySet()) {
			if (urlMap.get(key) != null)
				str += "&" + key + "=" + urlMap.get(key);
		}
		return str;
	}

	/**
	 * 判断对象数组中所有的元素为null, 或去除空格符之后长度为0 数组为空，则返回true
	 * 
	 * @param objects
	 *            常用类型 Date,String,Integer
	 * @return
	 */
	public static boolean isAllBlank(Object... objects) {
		if (objects == null)
			return true;
		for (int i = 0; i < objects.length; i++) {
			Object object = objects[i];
			if (object != null && !object.toString().trim().isEmpty())
				return false;
		}
		return true;
	}

	/**
	 * 判断对象数组中任意一个元素为null, 或去除空格符之后长度为0 数组为空，则返回true
	 * 
	 * @param objects
	 *            常用类型 Date,String,Integer
	 * @return
	 */
	public static boolean isAnyBlank(Object... objects) {
		if (objects == null)
			return true;
		for (int i = 0; i < objects.length; i++) {
			Object object = objects[i];
			if (object == null || object.toString().trim().isEmpty())
				return true;
		}
		return false;
	}

	/**
	 * 
	 * @param str
	 *            待操作的字符串
	 * @param regx
	 *            split 的字符
	 * @return 当str 为null或空字符串时，返回空集合
	 */
	public static List<String> arrayToList(String str, String regx) {
		List<String> strList = Lists.newArrayList();
		if (StringUtils.isBlank(str))
			return null;
		String[] array = str.split(regx);
		for (int i = 0; i < array.length; i++) {
			strList.add(array[i]);
		}
		return strList;
	}

	public static List<String> arrayToListTwo(String str, String regx) {
		List<String> strList = Lists.newArrayList();
		if (StringUtils.isBlank(str))
			return null;
		String[] array = str.split(regx);
		for (int i = 0; i < array.length; i++) {
			if (!array[i].contains("default")) {
				strList.add(array[i]);
			}
		}
		return strList;
	}

	// 计算包裹到库天数
	public Integer getDay(Date date) {
		if (date == null)
			return null;
		long s1 = date.getTime();// 将时间转为毫秒
		Date dayEnd = getDayEnd(DateTimeUtil.formatDate(new Date()));
		long s2 = dayEnd.getTime();

		return Integer.parseInt(String.valueOf((s2 - s1) / 1000 / 60 / 60 / 24));
	}

	/**
	 * 四舍五入，5及5以下舍，5以上入
	 * 
	 * @param value
	 * @return
	 */
	public static double formatTwo(double value) {
		BigDecimal bl = new BigDecimal(value);
		bl = bl.setScale(2, BigDecimal.ROUND_HALF_UP);
		return Double.parseDouble(bl.toString());
	}

	/**
	 * 校验手机号 1+任意10位数字 手机号
	 * 
	 * @param str
	 * @return
	 * @throws PatternSyntaxException
	 */
	public static boolean isPhoneLegal(String str) throws PatternSyntaxException {
		String regExp = "^1[0-9]{10}$";
		Pattern p = Pattern.compile(regExp);
		Matcher m = p.matcher(str);
		return m.matches();
	}

	/**
	 * 
	 * @Title: isEmail @Description: TODO(验证邮箱格式是否正确) @param @param
	 *         str @param @return 参数 @return boolean 返回类型 @throws
	 */
	public static boolean isEmail(String str) {
		java.util.regex.Pattern pattern = java.util.regex.Pattern
				.compile("^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$");
		java.util.regex.Matcher match = pattern.matcher(str);
		if (!match.matches()) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * 
	 * @Title: isMobile @Description: TODO(验证手机号格式是否正确) @param @param
	 *         str @param @return 参数 @return boolean 返回类型 @throws
	 */
	public static boolean isMobile(String str) {
		java.util.regex.Pattern pattern = java.util.regex.Pattern
				.compile("^(0|86|17951)?(13[0-9]|15[012356789]|17[013678]|18[0-9]|14[57])[0-9]{8}$");
		java.util.regex.Matcher match = pattern.matcher(str);
		if (!match.matches()) {
			return false;
		} else {
			return true;
		}
	}

	public static boolean isName(String str) {
		java.util.regex.Pattern pattern = java.util.regex.Pattern
				.compile("/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,8}$/\r\n");
		java.util.regex.Matcher match = pattern.matcher(str);
		if (!match.matches()) {
			return false;
		} else {
			return true;
		}
	}

	public static boolean isIdCard(String str) {
		java.util.regex.Pattern pattern = java.util.regex.Pattern.compile(
				"((11|12|13|14|15|21|22|23|31|32|33|34|35|36|37|41|42|43|44|45|46|50|51|52|53|54|61|62|63|64|65)[0-9]{4})"
						+ "(([1|2][0-9]{3}[0|1][0-9][0-3][0-9][0-9]{3}"
						+ "[Xx0-9])|([0-9]{2}[0|1][0-9][0-3][0-9][0-9]{3}))");
		java.util.regex.Matcher match = pattern.matcher(str);
		if (!match.matches()) {
			return false;
		} else {
			return true;
		}
	}

	public static final String REGITSTER_ACCOUNT_EMAIL = "REGISTER_ACCOUNT_EMAIL"; // 邮箱注册验证码
	public static final String RESTPASSWORD_ACCOUNT_EMAIL = "RESTPASSWORD_ACCOUNT_EMAIL"; // 邮箱注册验证码

	public void simpleSendMail(String domain, String email, String verification_code, String title, String type) {

		Map<String, Object> res = new HashMap<String, Object>();
		res.put("domain", domain);
		res.put("email", email);
		res.put("verification_code", verification_code);
		if (type.equals(REGITSTER_ACCOUNT_EMAIL)) {
			String mailContent = TemplateUtil.applyTemplateSimple("/email/activation.ftl", res);
			new AutoSendMail(email, email, "账号注册验证码邮件", mailContent).start();
		}
		if (type.equals(RESTPASSWORD_ACCOUNT_EMAIL)) {
			String mailContent = TemplateUtil.applyTemplateSimple("/email/resetpassword.ftl", res);
			new AutoSendMail(email, email, "账号密码重置邮件", mailContent).start();
		}
	}

	public Date getDayStart(String startTime) {
		return DateTimeUtil.getDayStart(StringUtils.isNotBlank(startTime) ? DateTimeUtil.parseDate(startTime) : null);
	}

	public Date getDayEnd(String endTime) {
		return DateTimeUtil.getDayEnd(StringUtils.isNotBlank(endTime) ? DateTimeUtil.parseDate(endTime) : null);
	}

	@Resource
	public HttpSession getSession;
	// updateUserImg , 上传图片，替换旧图片
	public static String USERDIR = "userimg";
	public static String ADMINDIR = "adminimg";
	public static String USER_AVATAR = "avatar";
	public static String IDCARD_IMGS = "idcard";
	public static String IDCARD_MERGE_IMGS = "idcardmerge";
	public static String OUTPACKAGE_ZIP = "outpackage_zip";

	/**
	 * /**
	 * 
	 * @param baseUrl
	 *            根路径
	 * @param str
	 *            拼接的路径 ， 若该路径上的部分目录不存在则创建这条路径上的目录
	 */
	public static void newDirisNotExists(String fileName, String baseUrl, String str) {
		File newDir = new File(fileName);
		if (!newDir.exists()) {
			String[] dirs = str.split("/");
			for (String string : dirs) {
				baseUrl = RequestUtil.mergeUrl(baseUrl, string);
				File file = new File(baseUrl);
				if (!file.exists()) {
					file.mkdirs();
				}
			}
		}
	}

	protected static String getFolderPath(String folder, String dirSpace, String userid) {
		if (userid != null && userid != "")
			return RequestUtil.mergeUrl(
					RequestUtil.mergeUrl(RequestUtil.mergeUrl(CommonConfig.getUploadPath(), dirSpace), userid), folder);
		return RequestUtil.mergeUrl(RequestUtil.mergeUrl(CommonConfig.getUploadPath(), dirSpace), folder);
	}

	public static String getFolderPath(String folder, String dirSpace) {
		return getFolderPath(folder, dirSpace, null);
	}
}
